package com.wang.example.netty.handler.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wang.basic.netty.handler.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class EchoClientInHandler1 extends ChannelInboundHandlerAdapter{

    /**读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //ByteBuf为netty实现的缓冲区
        ByteBuf in = (ByteBuf)msg;
        String msgStr = in.toString(CharsetUtil.UTF_8);
        System.out.println("EchoClientInHandler1 处理:" + msgStr);
        Message message = JSON.parseObject(msgStr,new TypeReference<Message>(){});
        ctx.fireChannelRead(message);
    }

    /**
     * 当Channel 处于活动状态时被调用；Channel 已经连接/绑定并且已经就绪
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("EchoClientInHandler1 channelActive");
    }
    /**
     * exceptionCaught()事件处理方法当出现Throwable对象才会被调用
     * 即当Netty由于IO错误或者处理器在处理事件时抛出的异常时
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
